Skip to main content

errno.h

errno variable

errno.h declares an errno variable of type int to store the error code (a positive integer).

If this variable has a non-zero value, it means that an error has occurred in the program that has been executed.

int x = -1;

errno = 0;

int y = sqrt(x);

if (errno ! = 0) {
fprintf(stderr, "sqrt error; program terminated.\n");
exit(EXIT_FAILURE);
}

In the above example, calculating the square root of a negative value is not allowed and will result in errno not being equal to 0.

To check if an error has occurred in a function, the value of errno must be set to 0 before the function is about to be called, preventing other functions from changing the value of errno.

Macros

The value of the variable errno is usually one of two macros EDOM or ERANGE. Both of these macros are defined in errno.h. They indicate two kinds of errors that can occur when calling mathematical functions.

  • Definition domain error (EDOM): one of the arguments passed to the function is out of the function's definition domain. For example, a negative number is passed as an argument to sqrt().
  • ERANGE (Error in Range): The return value of a function is too large to be represented by the return type. For example, 1000 is passed as an argument to exp() because e^1000 is too large to be represented by the double type.

When using mathematical functions, the value of errno can be compared with EDOM and ERANGE to determine what type of error has occurred.